﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace TestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string msg = "I am a sender";
            byte[] txData = Encoding.UTF8.GetBytes(msg);
            int len = txData.Length;
            MemoryStream pip = new MemoryStream();
            pip.WriteByte((byte)len);
            pip.Write(txData, 0, len);
            byte[] rep = pip.ToArray();

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            sock.Bind(
                new IPEndPoint(
                    IPAddress.Parse("192.168.212.101"), 8007)
                    );
            sock.Connect(
                new IPEndPoint(
                    IPAddress.Parse("192.168.212.101"), 10898)
                    );
            sock.Send(new byte[] { 0x01, 0xFF, 0xFF, 0xFF });

            byte[] r1 = new byte[1024];
            int c = sock.Receive(r1);
            if (c == 4)
            {
                int rs = r1[0] + r1[1] + r1[2] + r1[3];
                byte[] rep2 = BitConverter.GetBytes(rs);
                sock.Send(rep2);

                c = sock.Receive(r1);

                pip.SetLength(0);
                pip.Write(r1, 0, c);
                Console.WriteLine(Encoding.UTF8.GetString(pip.ToArray()));

                byte[] rep3 = BitConverter.GetBytes(DateTime.Now.Ticks);
                sock.Send(rep3);

                c = sock.Receive(r1);
                Console.WriteLine("Hands ok");
                
                sock.Send(rep);
                Console.WriteLine("send data :" + msg);
                byte[] buffer = new byte[1024];
                int count = sock.Receive(buffer);
                if (count > 0)
                {
                    pip.SetLength(0);
                    pip.Write(buffer, 0, count);
                    byte[] rply = pip.ToArray();
                    Console.WriteLine(Encoding.UTF8.GetString(rply));
                }
                sock.Send(rep);
                Console.WriteLine("send data :" + msg);
                //byte[] buffer = new byte[1024];
                count = sock.Receive(buffer);
                if (count > 0)
                {
                    pip.SetLength(0);
                    pip.Write(buffer, 0, count);
                    byte[] rply = pip.ToArray();
                    Console.WriteLine(Encoding.UTF8.GetString(rply));
                }
            }
            else
            {
                Console.WriteLine("auth false");
            }
            Console.Read();
            sock.Shutdown(SocketShutdown.Both);
            sock.Close();
            Console.Read();
            Console.Read();
        }
    }
}
